// Learn TypeScript:
//  - https://docs.cocos.com/creator/manual/en/scripting/typescript.html
// Learn Attribute:
//  - https://docs.cocos.com/creator/manual/en/scripting/reference/attributes.html
// Learn life-cycle callbacks:
//  - https://docs.cocos.com/creator/manual/en/scripting/life-cycle-callbacks.html

const {ccclass, property} = cc._decorator;


@ccclass
export default class SoldierScript extends cc.Component {

    @property(cc.Prefab)
    fab_body: cc.Prefab = null; // 身体

    @property(cc.Prefab)
    fab_bullet: cc.Prefab = null; // 子弹

    skinIndex: number = 0; // 皮肤类型

    minBulletNum: number = 5; // 最少子弹数量
    maxBulletNum: number = 10; // 最多子弹数量

    bulletBgColors: cc.Color[] = [
        new cc.Color().fromHEX('#3AB1FE'),
        new cc.Color().fromHEX('#57C316'),
        new cc.Color().fromHEX('#B10AFD'),
        new cc.Color().fromHEX('#D82C5A'),
        new cc.Color().fromHEX('#FDAB0E')
    ]

    // onLoad () {}

    // start () {}

    // update (dt) {}

    initHandler(skinIndex: number){
        skinIndex %= 5;
        this.createBodyHandler(skinIndex)
    }

    /**
     * 创建身体
     */
    createBodyHandler(skinIndex: number){
        const body: cc.Node = cc.instantiate(this.fab_body)
        this.skinIndex = body.getComponent('star').initHandler(skinIndex);
        body.parent = this.node;
    }

    //销毁
    destroyHandler(){
        const bulletNum: number = this.minBulletNum + Math.floor( Math.random() * 10 )

        for(let i = 0; i < bulletNum; i++){
            this.createBulletHandler()
        }

        const starnode = this.node.getChildByName('star')
        // console.log(starnode)
        starnode && starnode.removeFromParent()
    }

    createBulletHandler(){
        const bullet: cc.Node = cc.instantiate(this.fab_bullet)
        // console.log(this.skinIndex, 'skinIndex')
        const cor = this.bulletBgColors[this.skinIndex]
        bullet.getComponent('bulletScript').changeColorHandler(cor);

        const pos = this.node.getPosition();
        bullet.x = pos.x;
        bullet.y = pos.y;
        bullet.parent = this.node.parent;
    }
}
